// pages/course-detail/index.js
const app = getApp()
import {
  request
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    error:'',
    tabs: [],
    img: null,
    tag: [],
    price: null,
    title: '',
    activeTab: 1,
    tabSwiperHeight: 0,
    showQR: false,
    qrcode: null,
    savePhotosAlbum: false,
    formData: {},
    rules: [
    {
      name: 'name',
      rules: {
        required: true,
        message: '请输入姓名~'
      },
    },{
      name: 'phone',
      rules: {
        mobile: true,
        message: '请输入正确的手机号码~'
      },
    },
    {
      name: 'school',
      rules: {
        required: true,
        message: '请选择院校~'
      },
    },
    {
      name: 'level',
      rules: {
        required: true,
        message: '请选择层次~'
      },
    },
    {
      name: 'profession',
      rules: {
        required: true,
        message: '请选择专业~'
      },
    }],
    // 输入框的显示 (false) 和隐藏 (true)
    hideStatus: {
      name: true, // 姓名
      phone: true, // 手机
    },
    schoolArr: [],
    levelArr: [],
    professionArr: [],
    name: '', // 姓名
    phone: '', // 手机
    school: '', // 学校
    level: '', // 层次
    profession: '', // 专业

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // request('/api/index/config', app.globalData.token).then(res => {
    //   wx.downloadFile({
    //     url: res.data.wxapp_customer,
    //     success: (res) => {
    //       console.log(res, 'res');
    //       this.setData({
    //         qrcode: res.tempFilePath
    //       })
    //     }
    //   })
    // })
    request('/api/student/form', app.globalData.token).then(res => {
      console.log(res, 'school')
      if (res.code === 200) {
        console.log(res.data.info)
        let schoolArr = res.data.info instanceof Array ? res.data.info.map(item => item.title) : []
        console.log(schoolArr)
        this.setData({
          schoolArr: res.data.info
        })
      }
    })
    const {
      id
    } = options
    console.log(id)
    request('/api/product/info', app.globalData.token, 'get', {
      id
    }).then(res => {
      console.log(res)
      const tabs = [{
          title: '学校简介',
          desc: res.data.school_content
        },
        {
          title: '招生专业',
          desc: res.data.pro_content
        },
        {
          title: '报读条件',
          desc: res.data.con_content
        },
        {
          title: '证书样式',
          desc: res.data.certificate
        }
      ]
      if (!res.data.image || res.data.image.length <= 0) res.data.image = ['../../public/img/home_banner@2x.png']
      this.setData({
        tabs,
        img: res.data.image,
        tag: res.data.tag && res.data.tag instanceof Array && res.data.tag.splice(0, 2),
        price: res.data.price,
        title: res.data.title
      })
      this.setData({
        activeTab: 0
      })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  preventTouchMove: function () {},
  // 打开授权设置
  // openSettingTap() {
  //   if (!this.data.savePhotosAlbum) return
  //   console.log(222);
  //   const that = this
  //   wx.openSetting({
  //     withSubscriptions: true,
  //     success(res) {
  //       console.log(res)
  //       that.setData({
  //         savePhotosAlbum: !res.authSetting['scope.writePhotosAlbum']
  //       })
  //     },
  //     fail: err => {
  //       console.log(err)
  //     }
  //   })

  // },
  // // 保存二维码
  // saveQr() {
  //   // console.log(11);
  //   wx.getSetting({
  //     withSubscriptions: true,
  //     success: (res) => {
  //       console.log(res.authSetting['scope.writePhotosAlbum'])
  //       if (res.authSetting['scope.writePhotosAlbum'] !== false) {

  //         wx.saveImageToPhotosAlbum({
  //           filePath: this.data.qrcode,
  //           success(res) {
  //             console.log(res, 'saveImageToPhotosAlbum');
  //             wx.showToast({
  //               title: '保存图片成功',
  //               icon: 'success',
  //               duration: 2000
  //             })
  //           }
  //         })
  //       } else {
  //         // console.log(11);
  //         this.setData({
  //           savePhotosAlbum: true
  //         })
  //       }
  //     }
  //   })
  // },
  // 申请
  apply() {
    this.setData({
      showQR: !this.data.showQR
    })
    // console.log(this.data.showQR)
  },

  tabsSwiperHeight() {
    // tab 组件内的swiper高度自适应问题
    let index = this.data.activeTab;
    let queryDom = wx.createSelectorQuery()
    queryDom.select('.tab-content-' + index).boundingClientRect().exec(rect => {
      this.setData({
        tabSwiperHeight: rect[0].height
      })
    })
    console.log(this.data.tabSwiperHeight)
  },
  onChange(e) {
    const index = e.detail.index
    this.setData({
      activeTab: index
    })
    this.tabsSwiperHeight();
  },




  // 点击标题显示输入框
  handelshowInput(e) {
    console.log(e)
    const title = e.currentTarget.dataset.title
    const hideStatus = Object.assign({
      ...this.data.hideStatus,
      [title]: false
    })
    this.setData({
      hideStatus
    })
    // console.log(this.data.hideStatus)
  },
  // 失去焦点隐藏输入框
  handelHideInput(e) {
    const title = e.currentTarget.dataset.title
    const hideStatus = Object.assign({
      ...this.data.hideStatus,
      [title]: true
    })
    this.setData({
      hideStatus
    })
  },
  // 每一项的值变化触发的事件
  formItemChange(e) {
    // const code = e.detail.code
    let value = e.detail.value
    const field = e.currentTarget.dataset.field
    console.log(field, 'field');
    console.log(value, 'value');
    let formData = {}
    if (field === 'level' && this.data.school) {
      this.setData({
        professionArr: this.data.schoolArr[this.data.school].children[value].children
      })
    }
    if (field === 'level' && !this.data.school) {
      wx.showToast({
        title: '请先选择院校',
        icon: 'none'
      })
      return false
    }
    if (field === 'profession' && !this.data.level) {
      wx.showToast({
        title: '请先选择层次',
        icon: 'none'
      })
      return false
    }
    if (field === 'profession' && !this.data.school) {
      wx.showToast({
        title: '请先选择院校',
        icon: 'none'
      })
      return false
    }
    if (field === 'school') {
      formData = Object.assign(this.data.formData, {
        [field]: this.data.schoolArr[value].title
      })
    } else if (field === 'level' || field === 'profession') {
      formData = Object.assign(this.data.formData, {
        [field]: this.data.levelArr[value].title
      })
    }else if (field === 'profession') {
      formData = Object.assign(this.data.formData, {
        [field]: this.data.professionArr[value].title
      })
    }else {
      formData = Object.assign(this.data.formData, {
        [field]: value
      })
      
    }
    if (field === 'school') {
      console.log(this.data.schoolArr[value].children,2222)
      this.setData({
        levelArr: this.data.schoolArr[value].children,
        level:'',
        profession:'',
        professionArr:[]
      })
    }
    if (field === 'level') {
      this.setData({
        profession:'',
      })
    }
    console.log(field, value)
    console.log(e, 'www')

    this.setData({
      [field]: value,
      formData
    })
  },

  goNext() {
    this.selectComponent('#form').validate((valid, errors) => {
      console.log('valid', valid, errors)
      console.log('formData', this.data.formData)
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
          
        }
        setTimeout(() => {
          this.setData({
            error: ''
          })
        },2000)
      } else {
        request('/api/student/form', app.globalData.token, 'post', this.data.formData).then(res => {
          if (res.code === 200) {
            
            wx.showToast({
              title: '提交成功~',
              icon: 'none',
              duration: 1000,
              complete: () => {
                setTimeout(() => {
                  this.setData({
                    showQR: !this.data.showQR,
                      formData:{},
                      phone:'',
                      name:'',
                      school:'',
                      level:'',
                      profession:''
                  })
                }, 1000)

              }
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })

      }
    })


  },





  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})